package com.terios.logic.ui;

import java.util.HashMap;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.terios.AuthorizeUser;
import com.terios.R;
import com.terios.conts.CommonStrs;
import com.terios.intfs.IWeiboActivity;
import com.terios.logic.MainService;
import com.terios.logic.OAuth2Activity;
import com.terios.logic.Task;
import com.terios.sqlite.AuthorizeDAO;
import com.terios.util.Exit;
import com.terios.util.SaveLoginParam;
import com.terios.util.WeiboUtil;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboParameters;

/**
 * Login.java 2012-9-27 下午12:23:59
 * 
 * @author Wang Tengrui 登录页面，跳转到授权WebView
 */
public class LoginActivity extends Activity implements IWeiboActivity {

	public static WeiboParameters nowUserParameters;
	public static Weibo weibo;
	public static String token = null;
	public static String secret = null;

	public AuthorizeDAO authorizeDAO;
	public Spinner userSpinner;// 账户名下拉列表
	public ImageView loginPortrait;// 用户头像
	public Button loginBtn;// 登录按钮
	public Button newUserBtn;// 授权按钮
	public Dialog dialog;
	public ProgressDialog progressDialog;

	public static final int REFRESH_LOGIN = 1;// 登陆

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(getWindow().FEATURE_NO_TITLE);// 取消标题显示
		setContentView(R.layout.activity_login);
		MainService.allActivity.add(this);
		loginPortrait = (ImageView) findViewById(R.id.LoginPortrait);
		loginBtn = (Button) findViewById(R.id.loginBtn);
		newUserBtn = (Button) findViewById(R.id.newUserBtn);

		init();// 初始化activity

		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null == nowUserParameters.getValue("uid")) {
					Toast.makeText(LoginActivity.this, "首次使用，请点授权按钮",
							Toast.LENGTH_SHORT).show();
				} else {
					if (Long.parseLong(nowUserParameters
							.getValue("expires_date")) > System
							.currentTimeMillis()) {
						goHome();// 跳转到主界面
					} else {
						Toast.makeText(LoginActivity.this,
								"授权已经过期，请点击授权按钮重新授权", Toast.LENGTH_SHORT)
								.show();
					}
				}
			}
		});
		newUserBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				goOAuth(LoginActivity.this);
			}
		});
	}

	/**
	 * 登录初始化
	 */
	@Override
	public void init() {
		InitViewInfo();// 初始化Viewinfo
		if (WeiboUtil.checkNet(LoginActivity.this)) {
		} else {
			MainService.alertNetError(this);
		}
	}

	/**
	 * 登录页面初始化
	 */
	private void InitViewInfo() {
		nowUserParameters = SaveLoginParam.getNowUser(LoginActivity.this);
		if (nowUserParameters.getValue("uid") != null)// 如果uid不等于空
		{
			TextView tishiTextView = (TextView)findViewById(R.id.tishi);
			tishiTextView.setText("");
			authorizeDAO = new AuthorizeDAO(LoginActivity.this);
			AuthorizeUser authorizeUser = authorizeDAO.find(nowUserParameters
					.getValue("uid"));
			Bitmap bitmap = SaveLoginParam.Bytes2Bitmap(authorizeUser
					.getUserIcon());
			if (bitmap != null) {
				loginPortrait.setImageBitmap(bitmap);
			}

			token = authorizeUser.getAccess_token();
		} else {
			TextView tishiTextView = (TextView)findViewById(R.id.tishi);
			tishiTextView.setText(R.string.hintText);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 隐式意图启动MainService
		Log.i("LoginActivity", "Login-->onResume,隐式启动MainService");
		Intent intent = new Intent("com.terios.logic.MainService");
		this.startService(intent);
	}

	/**
	 * 跳转到主页面
	 */
	@SuppressWarnings("unchecked")
	public void goHome() {
		if (null == progressDialog) {
			progressDialog = new ProgressDialog(LoginActivity.this);
		}
		progressDialog.setMessage("正在登录中。。。");
		progressDialog.show();
		@SuppressWarnings("rawtypes")
		HashMap param = new HashMap();
		param.put("token", token);
		param.put("uid", nowUserParameters.getValue("uid"));

		Task loginTask = new Task(CommonStrs.TASK_USER_LOGIN, param);
		MainService.addTask(loginTask);
	}

	/**
	 * 授权
	 */
	public void goOAuth(Context context) {
		context.startActivity(new Intent(context, OAuth2Activity.class));

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Exit.btexit(LoginActivity.this);// 当我们按下返回键的时候要执行的动作
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void refresh(Object... param) {
		int flag = ((Integer) param[0]).intValue();// 获取第一个参数
		switch (flag) {
		case REFRESH_LOGIN:
			Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT)
					.show();
			Log.i("LoginActivity",
					"refresh()：" + "" + ((Integer) param[0]).intValue());
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			this.startActivity(new Intent(this, MainActivity.class));
			MainService.allActivity.remove(this);
			finish();
			break;

		}
	}
	
	/**
	 * 返回本activity的名字
	 * @return
	 * @author zxx
	 */
	public static String getMyName(boolean isShowPackage){
		if(isShowPackage){
			return LoginActivity.class.getPackage()+LoginActivity.class.getName();
		}else{
			return LoginActivity.class.getName();
		}
	}
}
